package com.seveneight.baijiesteward.http;

import android.accounts.NetworkErrorException;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.seveneight.baijiesteward.R;
import com.seveneight.baijiesteward.base.BaseActivity;
import com.seveneight.baijiesteward.base.MyApplication;
import com.seveneight.baijiesteward.bean.BaseEntity;
import com.seveneight.baijiesteward.utils.AppContextUtil;
import com.seveneight.baijiesteward.utils.LogUtil;
import com.seveneight.baijiesteward.utils.Setting;
import com.seveneight.baijiesteward.utils.StringUtils;
import com.seveneight.baijiesteward.utils.ToastUtil;
import com.seveneight.baijiesteward.views.ProgressDialog;

import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import io.reactivex.exceptions.UndeliverableException;
import retrofit2.HttpException;

/**
 * 有提示框
 */

public abstract class BaseObserver<T> implements Observer<BaseEntity<T>> {
    protected Context mContext;
    protected String message;

    public BaseObserver(Context context, String message) {
        this.mContext = context;
        this.message = message;
    }

    public BaseObserver(Context context) {
        this.mContext = context;
        message = "正在加载中...";
    }

    @Override
    public void onSubscribe(Disposable d) {
        onRequestStart();
    }

    @Override
    public void onNext(BaseEntity<T> tBaseEntity) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                onRequestEnd();
                if (tBaseEntity.isSuccess()) {
                    try {
                        LogUtil.d("success:" + tBaseEntity.toString());
                        onSuccees(tBaseEntity);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        LogUtil.d("error:" + tBaseEntity.toString());
                        onCodeError(tBaseEntity);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }, 500);
    }

    @Override
    public void onError(Throwable e) {
//        Log.w(TAG, "onError: ", );这里可以打印错误信息
        onRequestEnd();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            int code = httpException.code();
            if (code == 500 || code == 404) {
                ToastUtil.show(mContext, "连接失败，请稍后再试");
            } else if (code == 504) {
                ToastUtil.show(mContext, "请求失败，请检查网络连接");
            }
        } else if (e instanceof ConnectException) {
            ToastUtil.show(mContext, "网络断开,请打开网络");
        } else if (e instanceof SocketTimeoutException) {
            ToastUtil.show(mContext, "网络连接超时");
        } else if (e instanceof NoRouteToHostException) {
            ToastUtil.show(mContext, "无法连接到服务器");
        }
    }

    @Override
    public void onComplete() {

    }

    /**
     * 返回成功
     *
     * @param t
     * @throws Exception
     */
    protected abstract void onSuccees(BaseEntity<T> t) throws Exception;

    /**
     * 返回成功了,但是code错误
     *
     * @param t
     * @throws Exception
     */
    protected void onCodeError(final BaseEntity<T> t) throws Exception {
        hideDialog();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (t.getRespMsg().contains("用户标识不能为空") || t.getRespMsg().contains("找不到该用户信息")){
                    Setting.getInstance(mContext).setIsLogin(false);
                }
                ToastUtil.show(mContext, t.getRespMsg());
            }
        }, 500);
    }

    /**
     * 返回失败
     *
     * @param e
     * @param isNetWorkError 是否是网络错误
     * @throws Exception
     */
    protected abstract void onFailure(Throwable e, boolean isNetWorkError) throws Exception;

    protected void onRequestStart() {
        showDialog();
    }

    protected void onRequestEnd() {
        hideDialog();
    }

    private MaterialDialog.Builder builder;
    private MaterialDialog dialog;

    public void showDialog() {
        if (StringUtils.isEmpty(message))
            return;
        try {
            builder = new MaterialDialog.Builder(mContext)
                    .content(message)
                    .backgroundColorRes(R.color.white)
                    .cancelable(false)
                    .widgetColorRes(R.color.mainblue)
                    .contentColorRes(R.color.mainblue)
                    .progress(true, 0)
                    .progressIndeterminateStyle(false);
            dialog = builder.build();
            dialog.show();
        } catch (Exception ex) {

        }
    }

    public void hideDialog() {
        if (null!=dialog){
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }
}
